import { Space, Row, Col, Button, Typography, Checkbox, message, Form } from 'antd';
import ProCard from '@ant-design/pro-card';
import React, { useState, useRef, useEffect } from 'react';
import { getDvaApp, history, } from 'umi';
import ProForm, {
    ProFormText,
    ProFormSwitch,
    ProFormCheckbox,
} from '@ant-design/pro-form';
import $utils from '@/utils/utils';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import './index.less';
import { getJobDetail, addJob, updateJob, limitEnum } from '@/services/jobs';

const { Title, } = Typography;

const Detail: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;

    const [cur_id, setCur_id] = useState<string>();
    const [jobsDetail, setJobsDetail] = useState<any>();

    const [checked, setChecked] = useState<any>(false);

    const [deliveryList, setDeliveryList] = useState<any>([]);
    const [de_indeterminate, setDe_indeterminate] = useState(false);
    const [de_checkAll, setDe_checkAll] = useState(false);

    // 驿站
    const [postHouseList, setPostHouseList] = useState<any>([]);
    const [po_indeterminate, setPo_indeterminate] = useState(false);
    const [po_checkAll, setPo_checkAll] = useState(false);

    // imei
    const [imeiList, setImeiList] = useState<any>([]);
    const [imei_indeterminate, setImei_indeterminate] = useState(false);
    const [imei_checkAll, setImei_checkAll] = useState(false);

    // 号段
    const [numList, setNumList] = useState<any>([]);
    const [nu_indeterminate, setNu_indeterminate] = useState(false);
    const [nu_checkAll, setNu_checkAll] = useState(false);

    // 快递公司
    const [companyList, setCompanyList] = useState<any>([]);
    const [co_indeterminate, setCo_indeterminate] = useState(false);
    const [co_checkAll, setCo_checkAll] = useState(false);

    // 柜体
    const [cabinetList, setCabinetList] = useState<any>([]);
    const [cab_indeterminate, setCab_indeterminate] = useState(false);
    const [cab_checkAll, setCab_checkAll] = useState(false);

    // 代理商
    const [agentList, setAgentList] = useState<any>([]);
    const [age_indeterminate, setAge_indeterminate] = useState(false);
    const [age_checkAll, setAge_checkAll] = useState(false);

    const l_state: any = history.location.state;
    if (!cur_id && (!l_state || !l_state?.data)) {
        history.push('/order/delivery/list');
    }

    const id: string = l_state?.data?.id || '';
    //  同path更新,只更新state时，通过id重新请求数据
    if (l_state && id && (!cur_id || cur_id !== id)) {
        setCur_id(id);
    }
    else if (l_state && !id && cur_id !== id) {
        setCur_id('');
    }

    const isCreate: boolean = l_state?.status === 'create';
    const isUpdate: boolean = l_state?.status === 'update';
    const isDetail: boolean = l_state?.status === 'detail';

    const jobsNames = isCreate ? l_state?.data : [];

    const clearState = () => {
        setJobsDetail(undefined);
        setDeliveryList([]);
        setDe_indeterminate(false)
        setDe_checkAll(false);

        setPostHouseList([]);
        setPo_indeterminate(false);
        setPo_checkAll(false);

        setImeiList([]);
        setImei_indeterminate(false);
        setImei_checkAll(false);

        setNumList([]);
        setNu_indeterminate(false);
        setNu_checkAll(false);

        setCompanyList([]);
        setCo_indeterminate(false);
        setCo_checkAll(false);

        setCabinetList([]);
        setCab_indeterminate(false);
        setCab_checkAll(false);

        setAgentList([]);
        setAge_indeterminate(false);
        setAge_checkAll(false);
    };

    useEffect(() => {
        const getJobsDetail = async () => {
            try {
                const msg = await getJobDetail({ id: cur_id });
                if (msg.code === 0) {
                    let data = Object.assign({}, msg.body);
                    data.status = msg.body.status === 1;
                    setChecked(data.status);
                    const new_menuTree: any = {};
                    data.menuInfoList && data.menuInfoList.forEach((item: { id: number, name: string, URI: string }) => {
                        const limit = limitEnum.find(i => +item.URI === i.value);
                        if (limit) {
                            if (['deliveryAll', 'postHouseAll', 'imeiAll', 'numAll', 'companyAll', 'cabinetAll', 'agentAll'].includes(limit.key)) {
                                !new_menuTree[limit.key] && (new_menuTree[limit.key] = []);
                                new_menuTree[limit.key].push(limit.value);
                            }
                            else {
                                new_menuTree[limit.key] = true;
                            }
                        }
                    });

                    setDeliveryList(new_menuTree?.deliveryAll || []);
                    setDe_indeterminate(new_menuTree?.deliveryAll?.length < 6)
                    setDe_checkAll(new_menuTree?.deliveryAll?.length === 6);

                    setPostHouseList(new_menuTree?.postHouseAll || []);
                    setPo_indeterminate(new_menuTree?.postHouseAll?.length < 2);
                    setPo_checkAll(new_menuTree?.postHouseAll?.length === 2);

                    setImeiList(new_menuTree?.imeiAll || []);
                    setImei_indeterminate(new_menuTree?.imeiAll?.length < 3);
                    setImei_checkAll(new_menuTree?.imeiAll?.length === 3);

                    setNumList(new_menuTree?.numAll || []);
                    setNu_indeterminate(new_menuTree?.numAll?.length < 4);
                    setNu_checkAll(new_menuTree?.numAll?.length === 4);

                    setCompanyList(new_menuTree?.companyAll || []);
                    setCo_indeterminate(new_menuTree?.companyAll?.length < 3);
                    setCo_checkAll(new_menuTree?.companyAll?.length === 3);

                    setCabinetList(new_menuTree?.cabinetAll || []);
                    setCab_indeterminate(new_menuTree?.cabinetAll?.length < 4);
                    setCab_checkAll(new_menuTree?.cabinetAll?.length === 4);

                    setAgentList(new_menuTree?.agentAll || []);
                    setAge_indeterminate(new_menuTree?.agentAll?.length < 4);
                    setAge_checkAll(new_menuTree?.agentAll?.length === 4);

                    data = Object.assign({}, data, new_menuTree);
                    setJobsDetail(data);
                    formRef && formRef.current?.resetFields();
                    return;
                }
            } catch (error) {
                message.error(`${error}`);
            }
        };
        if (!cur_id) {
            clearState();
            formRef && formRef.current?.resetFields();
        }
        !isCreate && getJobsDetail();
    }, [cur_id]);

    const formRef = useRef<ProFormInstance>();

    return (
        <PageContainer>
            <ProCard style={{ marginTop: 8 }} gutter={8} >
                {(isCreate || jobsDetail) && <ProForm
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 18 }}
                    layout={"horizontal"}
                    formRef={formRef}
                    onFinish={async (values) => {
                        const { name, status, ...others } = values;
                        let menuIds: string | number[] = [];
                        // 订单管理 先将一级模块更新 boolean
                        deliveryList.length > 0 ? (others.order = true) : (others.order = false);
                        deliveryList.length > 0 ? (others.delivery = true) : (others.delivery = false);
                        // 基础配置 先将一级模块更新 boolean
                        (postHouseList.length + imeiList.length + numList.length + companyList.length + cabinetList.length + agentList.length) > 0 ? (others.basicConfig = true) : (others.basicConfig = false);
                        postHouseList.length > 0 ? (others.postHouse = true) : (others.postHouse = false);
                        imeiList.length > 0 ? (others.imei = true) : (others.imei = false);
                        numList.length > 0 ? (others.num = true) : (others.num = false);
                        companyList.length > 0 ? (others.company = true) : (others.company = false);
                        cabinetList.length > 0 ? (others.cabinet = true) : (others.cabinet = false);
                        agentList.length > 0 ? (others.agent = true) : (others.agent = false);
                        console.log('change value', others);

                        for (let k in others) {
                            const limit = limitEnum.find(i => i.key === k);
                            if (limit) {
                                if (['deliveryAll', 'postHouseAll', 'imeiAll', 'numAll', 'companyAll', 'cabinetAll', 'agentAll'].includes(limit.key)) {
                                    // menuIds = [...menuIds, ...others[k]];
                                }
                                else {
                                    others[k] && menuIds.push(limit.value);
                                }
                            }
                        }
                        deliveryList.length > 0 && (menuIds = [...menuIds, ...deliveryList]);
                        postHouseList.length > 0 && (menuIds = [...menuIds, ...postHouseList]);
                        imeiList.length > 0 && (menuIds = [...menuIds, ...imeiList]);
                        numList.length > 0 && (menuIds = [...menuIds, ...numList]);
                        companyList.length > 0 && (menuIds = [...menuIds, ...companyList]);
                        cabinetList.length > 0 && (menuIds = [...menuIds, ...cabinetList]);
                        agentList.length > 0 && (menuIds = [...menuIds, ...agentList]);

                        if (menuIds.length === 0) {
                            return message.warning('请至少选择一岗位权限');
                        }
                        let params = {
                            name: values.name,
                            status: values.status ? 1 : 2,
                            menuIds: menuIds.join(','),
                        };
                        if (isCreate) {
                            const msg = await addJob(params);
                            if (msg.code === 0) {
                                message.success('新增成功', 1, () => {
                                    // 设置当前tab对象
                                    $utils.setNewTab(dispatch, { name: '岗位管理', path: '/System/jobs', isTopMenu: true });
                                    history.push('/System/jobs');
                                });
                            }
                        }
                        else if (isUpdate) {
                            params = Object.assign(params, { id });
                            const msg = await updateJob(params);
                            if (msg.code === 0) {
                                message.success('编辑成功', 1, () => {
                                    // 设置当前tab对象
                                    $utils.setNewTab(dispatch, { name: '岗位管理', path: '/System/jobs', isTopMenu: true });
                                    history.push('/System/jobs');
                                });
                            }
                        }
                    }}
                    initialValues={isCreate ? undefined : jobsDetail}
                    submitter={{
                        render: (props, doms) => {
                            return [
                                <Space style={{ marginLeft: '8.33333338%' }}>
                                    {!isDetail && <Button type="primary" htmlType="submit">保存</Button>}
                                    <Button onClick={() => {
                                        // 设置当前tab对象
                                        $utils.setNewTab(dispatch, { name: '岗位管理', path: '/System/jobs', isTopMenu: true });
                                        history.push('/System/jobs');
                                    }}>取消</Button>
                                </Space>
                            ]
                        }
                    }}
                >
                    <Title level={4} style={{ marginBottom: 26 }}>基本信息</Title>
                    <Row>
                        <Col span={8}>
                            <ProFormText
                                width={'md'}
                                name="name"
                                label={'岗位名称'}
                                disabled={isDetail || isUpdate}
                                fieldProps={{
                                    maxLength: 15,
                                }}
                                rules={[
                                    {
                                        required: true,
                                    },
                                    {
                                        max: 15,
                                    },
                                    ({ getFieldValue }) => ({
                                        validator(_, value) {
                                            const index = jobsNames.findIndex((item: any) => item.label === value);
                                            if (index > -1) {
                                                return Promise.reject(new Error('岗位名称已存在'))
                                            }
                                            return Promise.resolve();
                                        }
                                    })
                                ]}
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormSwitch
                                name="status"
                                label="岗位状态"
                                disabled={isDetail}
                                checkedChildren="启用"
                                unCheckedChildren="禁用"
                                initialValue={false}
                                fieldProps={{
                                    checked: checked,
                                    onClick: (checked) => {
                                        console.log(checked);
                                        if (jobsDetail && jobsDetail.isUsing) {
                                            setChecked(true);
                                            message.warning('该岗位存在登录账号正在使用，不可禁用！');
                                        }
                                        else {
                                            setChecked(checked);
                                        }
                                    }
                                }}
                                rules={[
                                    {
                                        required: true,
                                    },

                                ]}
                            />
                        </Col>
                    </Row>
                    <Title level={4} style={{ marginBottom: 26 }}>权限设置</Title>
                    <Row>
                        <Col span={24}>
                            <div className="item">
                                <ProFormCheckbox
                                    className={'zk-strong'}
                                    disabled={isDetail}
                                    name="overview"
                                >
                                    概览
                                </ProFormCheckbox>
                            </div>
                            <div className="item">
                                <ProFormCheckbox
                                    className={'zk-strong'}
                                    disabled={isDetail}
                                    name="order"
                                    fieldProps={{
                                        checked: deliveryList.length > 0,
                                        onChange: (e) => {
                                            setDeliveryList(e.target.checked ? [110101, 110102, 110103, 110104, 110105] : []);
                                            setDe_indeterminate(false);
                                            setDe_checkAll(e.target.checked);
                                        }
                                    }}
                                >
                                    订单管理
                                </ProFormCheckbox>
                                <div className="level-2">
                                    <ProFormCheckbox
                                        name="delivery"
                                        className={'zk-strong'}
                                        disabled={isDetail}
                                        fieldProps={{
                                            indeterminate: de_indeterminate,
                                            checked: de_checkAll,
                                            onChange: (e) => {
                                                setDeliveryList(e.target.checked ? [110101, 110102, 110103, 110104, 110105] : []);
                                                setDe_indeterminate(false);
                                                setDe_checkAll(e.target.checked);
                                            }
                                        }}
                                    >
                                        派件业务
                                    </ProFormCheckbox>
                                </div>
                                <div className="level-3">
                                    <ProFormCheckbox.Group
                                        name="deliveryAll"
                                        layout={'horizontal'}
                                        disabled={isDetail}
                                        fieldProps={{
                                            value: deliveryList,
                                            onChange: (list) => {
                                                setDeliveryList(list);
                                                setDe_indeterminate(!!list.length && list.length < 6);
                                                setDe_checkAll(list.length === 6);
                                            }
                                        }}
                                        options={[{ label: '查询/重置', value: 110101 }, { label: '修改手机号', value: 110102 }, { label: '点此出库', value: 110103 }, { label: '点此退回', value: 110104 }, { label: '重发短信', value: 110105 }, { label: '重发柜体', value: 110106 }]}
                                    />
                                </div>
                            </div>
                            <div className="item">
                                <ProFormCheckbox
                                    name="basicConfig"
                                    disabled={isDetail}
                                    fieldProps={{
                                        checked: (postHouseList.length > 0 || imeiList.length > 0 || numList.length > 0 || companyList.length > 0 || cabinetList.length > 0 || agentList.length > 0),
                                        onChange: (e) => {
                                            setPostHouseList(e.target.checked ? [120101, 120102,] : []);
                                            setPo_indeterminate(false);
                                            setPo_checkAll(e.target.checked);

                                            setImeiList(e.target.checked ? [120401, 120402, 120403] : []);
                                            setImei_indeterminate(false);
                                            setImei_checkAll(e.target.checked);

                                            setNumList(e.target.checked ? [120201, 120202, 120203, 120204] : []);
                                            setNu_indeterminate(false);
                                            setNu_checkAll(e.target.checked);

                                            setCompanyList(e.target.checked ? [120301, 120302, 120303] : []);
                                            setCo_indeterminate(false);
                                            setCo_checkAll(e.target.checked);

                                            setCabinetList(e.target.checked ? [120501, 120502, 120503, 120504] : []);
                                            setCab_indeterminate(false);
                                            setCab_checkAll(e.target.checked);

                                            setAgentList(e.target.checked ? [120601, 120602, 120603, 120604] : []);
                                            setAge_indeterminate(false);
                                            setAge_checkAll(e.target.checked);
                                        }
                                    }}
                                >
                                    基础配置
                                </ProFormCheckbox>
                                {/* postHouse start */}
                                <div className="level-2">
                                    <ProFormCheckbox
                                        name="postHouse"
                                        className={'zk-strong'}
                                        disabled={isDetail}
                                        fieldProps={{
                                            indeterminate: po_indeterminate,
                                            checked: po_checkAll,
                                            onChange: (e) => {
                                                setPostHouseList(e.target.checked ? [120101, 120102,] : []);
                                                setPo_indeterminate(false);
                                                setPo_checkAll(e.target.checked);
                                            }
                                        }}
                                    >
                                        驿站管理
                                    </ProFormCheckbox>
                                </div>
                                <div className="level-3">
                                    <ProFormCheckbox.Group
                                        name="postHouseAll"
                                        disabled={isDetail}
                                        layout={'horizontal'}
                                        fieldProps={{
                                            value: postHouseList,
                                            onChange: (list) => {
                                                setPostHouseList(list);
                                                setPo_indeterminate(!!list.length && list.length < 2);
                                                setPo_checkAll(list.length === 2);
                                            }
                                        }}
                                        options={[{ label: '查询/重置', value: 120101 }, { label: '编辑', value: 120102 },]}
                                    />
                                </div>
                                {/* postHouse end */}

                                {/* IMEI start */}
                                <div className="level-2">
                                    <ProFormCheckbox
                                        name="imei"
                                        className={'zk-strong'}
                                        disabled={isDetail}
                                        fieldProps={{
                                            indeterminate: imei_indeterminate,
                                            checked: imei_checkAll,
                                            onChange: (e) => {
                                                setImeiList(e.target.checked ? [120401, 120402, 120403] : []);
                                                setImei_indeterminate(false);
                                                setImei_checkAll(e.target.checked);
                                            }
                                        }}
                                    >
                                        IMEI管理
                                    </ProFormCheckbox>
                                </div>
                                <div className="level-3">
                                    <ProFormCheckbox.Group
                                        name="imeiAll"
                                        disabled={isDetail}
                                        layout={'horizontal'}
                                        fieldProps={{
                                            value: imeiList,
                                            onChange: (list) => {
                                                setImeiList(list);
                                                setImei_indeterminate(!!list.length && list.length < 3);
                                                setImei_checkAll(list.length === 3);
                                            }
                                        }}
                                        options={[{ label: '查询/重置', value: 120401 }, { label: '新建', value: 120402 }, { label: '删除', value: 120403 },]}
                                    />
                                </div>
                                {/* IMEI end */}

                                {/* Num start */}
                                <div className="level-2">
                                    <ProFormCheckbox
                                        name="num"
                                        className={'zk-strong'}
                                        disabled={isDetail}
                                        fieldProps={{
                                            indeterminate: nu_indeterminate,
                                            checked: nu_checkAll,
                                            onChange: (e) => {
                                                setNumList(e.target.checked ? [120201, 120202, 120203, 120204] : []);
                                                setNu_indeterminate(false);
                                                setNu_checkAll(e.target.checked);
                                            }
                                        }}
                                    >
                                        号段管理
                                    </ProFormCheckbox>
                                </div>
                                <div className="level-3">
                                    <ProFormCheckbox.Group
                                        name="numAll"
                                        layout={'horizontal'}
                                        disabled={isDetail}
                                        fieldProps={{
                                            value: numList,
                                            onChange: (list) => {
                                                setNumList(list);
                                                setNu_indeterminate(!!list.length && list.length < 4);
                                                setNu_checkAll(list.length === 4);
                                            }
                                        }}
                                        options={[{ label: '查询/重置', value: 120201 }, { label: '新建运单号段', value: 120202 }, { label: '编辑', value: 120203 }, { label: '删除', value: 120204 },]}
                                    />
                                </div>
                                {/* Num end */}

                                {/* company start */}
                                <div className="level-2">
                                    <ProFormCheckbox
                                        name="company"
                                        className={'zk-strong'}
                                        disabled={isDetail}
                                        fieldProps={{
                                            indeterminate: co_indeterminate,
                                            checked: co_checkAll,
                                            onChange: (e) => {
                                                setCompanyList(e.target.checked ? [120301, 120302, 120303] : []);
                                                setCo_indeterminate(false);
                                                setCo_checkAll(e.target.checked);
                                            }
                                        }}
                                    >
                                        快递公司
                                    </ProFormCheckbox>
                                </div>
                                <div className="level-3">
                                    <ProFormCheckbox.Group
                                        name="companyAll"
                                        disabled={isDetail}
                                        layout={'horizontal'}
                                        fieldProps={{
                                            value: companyList,
                                            onChange: (list) => {
                                                setCompanyList(list);
                                                setCo_indeterminate(!!list.length && list.length < 3);
                                                setCo_checkAll(list.length === 3);
                                            }
                                        }}
                                        options={[{ label: '查询/重置', value: 120301 }, { label: '新建快递公司', value: 120302 }, { label: '编辑', value: 120303 },]}
                                    />
                                </div>
                                {/* company end */}

                                {/* cabinet start */}
                                <div className="level-2">
                                    <ProFormCheckbox
                                        name="cabinet"
                                        className={'zk-strong'}
                                        disabled={isDetail}
                                        fieldProps={{
                                            indeterminate: cab_indeterminate,
                                            checked: cab_checkAll,
                                            onChange: (e) => {
                                                setCabinetList(e.target.checked ? [120501, 120502, 120503, 120504] : []);
                                                setCab_indeterminate(false);
                                                setCab_checkAll(e.target.checked);
                                            }
                                        }}
                                    >
                                        柜体管理
                                    </ProFormCheckbox>
                                </div>
                                <div className="level-3">
                                    <ProFormCheckbox.Group
                                        name="cabinetAll"
                                        disabled={isDetail}
                                        layout={'horizontal'}
                                        fieldProps={{
                                            value: cabinetList,
                                            onChange: (list) => {
                                                setCabinetList(list);
                                                setCab_indeterminate(!!list.length && list.length < 4);
                                                setCab_checkAll(list.length === 4);
                                            }
                                        }}
                                        options={[{ label: '查询/重置', value: 120501 }, { label: '新建', value: 120502 }, { label: '编辑', value: 120503 }, { label: '删除', value: 120504 },]}
                                    />
                                </div>
                                {/* cabinet end */}

                                {/* agent start */}
                                <div className="level-2">
                                    <ProFormCheckbox
                                        name="agent"
                                        className={'zk-strong'}
                                        disabled={isDetail}
                                        fieldProps={{
                                            indeterminate: age_indeterminate,
                                            checked: age_checkAll,
                                            onChange: (e) => {
                                                setAgentList(e.target.checked ? [120601, 120602, 120603, 120604] : []);
                                                setAge_indeterminate(false);
                                                setAge_checkAll(e.target.checked);
                                            }
                                        }}
                                    >
                                        代理商管理
                                    </ProFormCheckbox>
                                </div>
                                <div className="level-3">
                                    <ProFormCheckbox.Group
                                        name="agentAll"
                                        disabled={isDetail}
                                        layout={'horizontal'}
                                        fieldProps={{
                                            value: agentList,
                                            onChange: (list) => {
                                                setAgentList(list);
                                                setAge_indeterminate(!!list.length && list.length < 4);
                                                setAge_checkAll(list.length === 4);
                                            }
                                        }}
                                        options={[{ label: '查询/重置', value: 120601 }, { label: '新建', value: 120602 }, { label: '编辑', value: 120603 }, { label: '删除', value: 120604 },]}
                                    />
                                </div>
                                {/* agent end */}
                            </div>
                        </Col>
                    </Row>
                </ProForm>}
            </ProCard>
        </PageContainer>
    );
};

export default Detail;
